<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的多应用管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.niucloud.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------

namespace app\service\core\order;

use app\dict\member\MemberAccountTypeDict;
use app\dict\order\OrderDeliveryDict;
use app\dict\order\OrderDict;
use app\dict\order\OrderGoodsDict;
use app\api\model\order\Order;
use app\api\model\order\OrderGoods;
use app\service\core\member\CoreMemberAccountService;
use app\service\core\order\CoreOrderEventService;
use app\core\base\BaseCoreService;
use app\core\exception\CommonException;

/**
 *  订单完成服务层
 */
class CoreOrderFinishService extends BaseCoreService
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new Order();
    }


    /**
     * 订单完成
     * @param $data
     * @return true
     */
    public function finish($order,$afterData,$data=[])
    {
        $update_data = array(
            'status' => OrderDict::FINISH,
            'finish_time' => time(),
            'timeout' => 0,
        );
        if($order['is_consult'] == 1){
            // 协商单
            $goodsMoney = $order['consult_money'];
            $remark = '用户同意协商';
        }else{
            $update_data['shop_remark'] = $data['remark']??'';
            $update_data['unboxing_video'] = $data['unboxing_video']??'';
            $goodsMoney = $order['goods_money'];
            $remark = '后台订单收货';
        }
        $this->model->where('order_id',$order['order_id'])->update($update_data);
        //订单项收货
        $this->orderGoodsTake($order);
        //会员余额
        (new CoreMemberAccountService())->addLog($order['member_id'], MemberAccountTypeDict::BALANCE, $goodsMoney, 'order_finish', $remark, $order['order_id']);
        $afterData['order_data'] = array_merge($order, $update_data);

        //订单完成后操作
        CoreOrderEventService::orderFinishAfter($afterData);
        return true;
    }




    /**
     * 订单项收货
     * @param $data
     * @return void
     */
    public function orderGoodsTake($data)
    {
        $order_id = $data['order_id'];
        //将待收货的订单项设置已收货
        $order_goods_where = array(
            ['order_id', '=', $order_id],
            ['status', '=', OrderGoodsDict::NORMAL],
//            ['delivery_status', '=', OrderDeliveryDict::DELIVERY_FINISH]
        );
        $order_goods_data = array(
            'delivery_status' => OrderDeliveryDict::TAKED
        );
        (new OrderGoods())->where($order_goods_where)->update($order_goods_data);
        return true;
    }
}
